package br.com.portalecbahia.connectionservices;

import org.json.JSONArray;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import blueprint.software.blueframe.synchronize.HTTPConnect;
import br.com.portalecbahia.dao.NewsDAO;
import br.com.portalecbahia.listner.NewsListeners;
import br.com.portalecbahia.util.PortalECBahiaUtil;

public class SynchronizeNews extends AsyncTask<Void, Void, Boolean> {

	private NewsListeners listeners;
	private HTTPConnect connect;
	private NewsDAO dao;
	private Context context;
	
	public SynchronizeNews (Context context){
	
		this.context = context;
		
		this.listeners = (NewsListeners)context;
	}
	
	@Override
	protected void onPreExecute() {
	
	}
	
  
    @Override
    protected void onPostExecute(Boolean result) {               
       
       	listeners.onSynchronizeNewsComplete(result);
   }

	@Override
	protected Boolean doInBackground(Void... params) {
		
		try{
			connect = new HTTPConnect(PortalECBahiaUtil.urlServer+"/FindAllNews");
			JSONArray jsonArray =  connect.getArray("", null);
			
			if(jsonArray!=null && jsonArray.length()>0){
				dao = new NewsDAO(context);
				dao.removeAll();
				dao.insert(jsonArray);	
				dao.getLimits();
			}
			
		}catch (Exception e) {
			Log.e(PortalECBahiaUtil.TAG, e.toString());
			return false;
		}
		
		return true;
	}
}

